<?php
class User extends AppModel {
	var $name = 'User';
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'UserRole' => array(
			'className' => 'UserRole',
			'foreignKey' => 'user_role_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	var $hasMany = array(
		'Permit' => array(
			'className' => 'Permit',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		),
		'UserAction' => array(
			'className' => 'UserAction',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

    /**
     * Returns the first user that matches the credentials for the login process
     * 
     * @param type $username
     * @param type $password
     * @return type 
     */
    public function findForLogin($username, $password) {
        return $this->find('first', array(
            'contain' => array('UserRole'),
            'conditions' => array(
                'User.username' => $username,
                'User.password' => md5($password)
            )
        ));
    }
    
    public function updateLogin($id) {
        $this->id = intval($id);
        $this->set('last_access_dt', date('Y-m-d H:i:s'));
        $this->save();
        
        //$this->recordAction($id, $id, "Log In: " . $this->getDisplayValue());
    }
    
    public function updateLogout($user_id) {
        $this->id = $user_id;
        //$this->recordAction($user_id, $user_id, "Log Out: " . $this->getDisplayValue());
    }
    
    public function getDisplayValue() {
        return $this->field('first_name') . " " . $this->field("last_name");
    }
    
    public function createNewUser() {
        
        if( !isset($_POST['data']['User']) ) {
            return false;
        }
        
        $this->create();
        $this->set($_POST['data']['User']);
        $this->set( array(
            'password' => md5($_POST['data']['User']['password'])
        ));
        
        return $this->save();
    }
    
    function isSuperUser() {
        return $_SESSION['user']['User']['user_role_id'] == 1;
    }
}
?>